<template>
    <div class="main-content">
        <div class="title">
            <span class="info">业务部门
            </span>
            <div>
              <Button
                type="primary" size="middle"
                icon="md-add" class="item"
                @click="addDepart"  
                >新建</Button>
              <Button size="middle" class="item" @click="refersh" >刷新</Button>
            </div>
        </div>
        <div class="tree-wrap">
            <Tree :data="departments" :render="renderContent"></Tree>
        </div>
        <Loader :status="status" @refresh="refersh"></Loader>
        <AddNodeItem ref="addNodeItem" @cancel='onCancelEditItem' @confirm='onConfirmEditItem' />
        <EditNodeItem ref="editNodeItem" @removeDepart='removeDepart' @confirm='onConfirmEditItem' />
    </div>
</template>
<script>
import { Tooltip, Icon, Input, Button, Poptip } from 'view-design';
import { guid } from '@/util';
import AreaSelect from '~/AreaSelect';
import AddNodeItem from "./AddNodeItem";
import EditNodeItem from './EditNodeItem'

let className = 'tree-item ivu-tree-gather';
let dragedData = null;
let dragoverData = null;
let positionStatusClass = null;
let position = null;

export default {
  components: {
    Tooltip,Icon,AreaSelect,AddNodeItem, EditNodeItem
  },
  props: {
  },
  data() {
    return {
      tab: 'tab1',
      split: 0.51,
      status: 'pass',
      departments: [
      ],
      curClickNode: null,
      curAddChildNode: {}
    }
  },
  created() {
    this.getData()
  },
  methods: {
    refersh() {
      this.getData()
    },
    getData (){
      this.status = 'loading'
      this.$jsonPost('/department/listDepartmentTree').then(res => {
        this.status = 'pass'
        this.departments = res.map(item => {
          if (item.children && item.children.length) {
            item.bindDistributorCount = item.children.reduce((t, c) => {
              return t + (c.bindDistributorCount || 0)
            }, 0)
          }
          return item
        })
      }).catch(err => {
        this.status = 'error'
      })
    },
    isNodeEditing() {
      let have = false
      const loop = (arr) => {
        arr.forEach(item =>{
          if (item.editing) {
            have = true
          }
          if (!have && item.children && item.children.length) {
            loop(item.children)
          }
        })
      }
      loop(this.departments)
      return have
    },
    renderAddIcon(h, { root, node, data }) {
      return (
        <a
          style={data.level < 3 ? 'font-size:12px':'cursor: not-allowed;color:#a1a8b9;font-size:12px'}
          class='mr'
          onClick={(e) => {
            e.stopPropagation();
            this.editNode(root, node, data);
          }}>编辑</a>
        )
    },
    renderContent (h, { root, node, data }) {
      return(
        <div
          draggable="true"
          on-dragstart={(e) => this.dragstart(e, {root, node, data})}
          on-dragenter={(e) => this.dragenter(e, {root, node, data})}
          on-dragover={(e) => this.dragover(e, {root, node, data})}
          on-dragend={(e) => this.dragend(e, {root, node, data})}
          onClick={(e) => { this.onClickItem(root, node, data) }}
          class={['tree-item', 'ivu-tree-gather', data.selected?'selected':'']}>
          <span class='left-info'>
            <span class={['ivu-tree-title']}>
              {<Icon type="ios-folder" />  }
              {(<span>
                {
                  <span
                    onDblclick={(event) => {
                      this.onEditItem(root, node, data)
                    }}
                    >
                    {data.name}({data.bindDistributorCount})
                  </span>
                }
              </span> )}
              
            </span>
          </span>
          <span class='right-opt'>
            { this.renderAddIcon(h, { node, root, data }) }     
          </span>
        </div>
      ) 
    },
    addDepart() {
      // let sort = this.departments.length+1;
      // let obj =  {
      //   name: '客车轮胎销售部',
      //   expand: true,
      //   type: 'dpt',
      //   editing: false,
      //   sort,
      //   level: 1,
      //   id: '',
      //   parentId: 0,
      //   children: [
      //   ]
      // }
      // this.departments.push(obj);
      this.curAddChildNode = this.departments; // 保存当前正在新增节点的数据
      // this.changeCurClickNode();
      this.$refs.addNodeItem.open()
    },
    // 编辑
    editNode (root, node, data) {
      this.$refs.editNodeItem.open(data)
    },
    // 编辑节点
    onEditItem(root, node, data) {
      event.stopPropagation();
      // this.$set(data, 'editing', true);
      let parentNode = root.find(item => item.node.id === data.parentId) || {}
      this.$refs.addNodeItem.open(data, parentNode.node || {})
    },
    // 点击节点
    onClickItem(root, node, data) {
      this.changeCurClickNode(data);
      let v = data.expand ? false : true
      const loop = (arr) => {
        arr.forEach(item => {
          item.selected = false
          if(item.children && item.children.length) {
            loop(item.children)
          }
        })

      }
      loop(this.departments)
      if(event.target.nodeName != "INPUT") {
        this.$set(data, 'expand', v);
      }
      this.$set(data, 'selected', true);
      this.$store.commit('setCurrentDepartment', data)
    },
    // 删除没有成功创建的节点
    romovNotSuccessAddNode() {
      if(Object.prototype.toString.call(this.curAddChildNode) === "[object Array]") { // 最外层节点
        this.departments = this.curAddChildNode = this.curAddChildNode.filter(e => e.id)
      } else {
        this.curAddChildNode.children = this.curAddChildNode.children.filter(e => e.id)
      }
    },
    // 取消编辑节点
    onCancelEditItem(root, node, data) {
    },
    // 确定编辑节点
    onConfirmEditItem(root, node, data) {
      this.status = 'loading'
      if (!data.id) { // 新增
        let supplierDepartmentDTO = {
          parentId: data.parentId || '0',
          sort: data.sort,
          name: data.name,
        }
        this.$jsonPost('/department/saveDepartment', supplierDepartmentDTO).then(res => {
          this.status = 'pass'
          this.$refs.addNodeItem.close()
          this.getData()
        }).catch(err => {
          this.status = 'pass'
        })
      } else {
        let supplierDepartmentDTO = {
          id: data.id,
          parentId: data.parentId,
          sort: data.sort,
          name: data.name,
        }
        this.$jsonPost('/department/modify', supplierDepartmentDTO).then(res => {
          this.status = 'pass'
          this.$Notice.success({ title: '修改成功' })
          this.$refs.editNodeItem.close()
        }).catch(err => {
          this.status = 'error'
        })
      }
    },
    // 编辑节点输入框失焦
    onEditInputBlurItem(root, node, data) {
      this.$set(data, 'editing', false)
    },
    // 编辑节点输入框值改变
    onEditItemInputValueChange($event, root, node, data) {
      let val = $event.target.value;
      data.name = val;
      this.$set(data, 'newname', val);
    },
    // 移除节点
    remove (root, node, data) {
      let id = data.id;
      let isfind = false;
      this.$jsonPost(`/department/delete/${id}`, {id}).then(res => {
        this.$Notice.success({
          title: '删除成功'
        })
      })
    },
    removeDepart(data) {
      this.getData()
    },
    dragstart(e, {root, node, data}) {
      data.expand = false
      let {dataTransfer, target} = e;
      dataTransfer.setData('text/plain', '');
      dataTransfer.effectAllowed = 'move';
      while (target.tagName !== 'DIV' && !target.classList.contains('ivu-tree-gather')) {
          target = target.parentNode
      }
      dragedData = node;
    },
    dragenter(e) {
      e.dataTransfer.dropEffect = 'move'
    },
    dragover(e, {root, node, data}) {
      let {target, offsetY} = e;
      e.preventDefault();
      while (target.tagName !== 'DIV' && !target.classList.contains('ivu-tree-gather')) {
          target = target.parentNode
      }
      if (dragedData !== node) {
          this.clearBorder();
          let positonStatus = offsetY / target.offsetHeight;
          if (positonStatus <= 1 / 3) {
              position = 1;
              positionStatusClass = ' ivu-tree-before';
          } else if (positonStatus > 1 / 3 && positonStatus < 2 / 3) {
              position = 2;
              positionStatusClass = ' ivu-tree-over'
          } else if (positonStatus >= 2 / 3) {
              position = 3;
              positionStatusClass = ' ivu-tree-after';
          }
          target.className = className + positionStatusClass;
          dragoverData = node;
      }
    },
    dragend(e, {root, node, data}) {
      let {target, offsetY} = e;
      let arr = this.getTargetArr(this.departments, data.id);
      let val = Math.floor(offsetY / target.offsetHeight);
      let length = arr.length;
      let index = arr.findIndex(e => e.id === data.id);
      if (val > 0) {
        let changedIdx = val > length ? length-1 : index + val - 1;
        let cur = arr.splice(index, 1)[0];
        arr.splice(changedIdx, 0, cur)
        this.reSetSort(arr);
      } else if (val < 0) {
        let changedIdx = val + index + 1 < 0 ? 0 : val + index + 1;
        let cur = arr.splice(index, 1)[0];
        arr.splice(changedIdx, 0, cur)
        this.reSetSort(arr);
      }

      this.clearBorder();
      dragedData = null;
      dragoverData = null;
      positionStatusClass = null;
      position = null;
    },
    getTargetArr(arr, id) {
      let val = [];
      function loop(arr, id) {
        for(let i = 0, len = arr.length; i < len; i++) {
          if (arr[i].id === id) {
            val = arr;
            break;
          }
          if (arr[i].children && arr[i].children.length) {
            loop(arr[i].children, id);
          }
        }
      }
      loop(arr, id)
      return val;
    },
    reSetSort(arr) {
      let sortObj = {}
      let val = arr.map((item, idx) => {
        let obj = { id: item.id, sort: idx+1 }
        item.sort = idx+1
        sortObj[item.id] = item.sort
        return obj;
      })
      // 调排序接口
      this.$jsonPost('/department/changeDepartmentOrder', sortObj)
    },

    clearBorder() {
        let borderElem = document.querySelectorAll('.ivu-tree-before,.ivu-tree-over,.ivu-tree-after');
        for (let i = 0; i < borderElem.length; i++) {
            borderElem[i].className = className;
        }
    },
    changeCurClickNode(data) {
      this.curClickNode = data;
      this.$emit('changeCurClickNode', data);
    },
  },
}
</script>
